package com.jx.demo.service;

import com.github.benmanes.caffeine.cache.Cache;
import com.jx.demo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserService {

    @Autowired
    private Cache<String,Object> caffeineCache;

    //模拟数据库
    private Map<Integer, User> userMap=new HashMap<>();

    public void add(User user){
        userMap.put(user.getId(),user);
        //添加缓存
        caffeineCache.put(String.valueOf(user.getId()),user);
    }

    public User get(Integer id){
        //获缓存中获取
        User user= (User) caffeineCache.asMap().get(String.valueOf(id));
        if(Objects.nonNull(user)){
            return user;
        }
        //缓存没有，从数据库获取
        user=userMap.get(id);
        if(Objects.nonNull(user)){
            //添加缓存
            caffeineCache.put(String.valueOf(id),user);
        }
        return user;
    }

    public void update(User user){
        //更新数据库
        userMap.put(user.getId(),user);
        //更新缓存
        caffeineCache.put(String.valueOf(user.getId()),user);
    }

    public void delete(Integer id){
        //删除数据库
        userMap.remove(id);
        //删除缓存
        //caffeineCache.put(String.valueOf(id),null);
        caffeineCache.asMap().remove(String.valueOf(id));
    }
}
